<template>
	<view class="recharge-card">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 充值卡信息 -->
		<view class="card-header">
			<view class="card-title">{{cardInfo.cardName || '加载中...'}}</view>
			<view class="price-row">
				<view class="price-container">
					<text class="before-price" v-if="cardInfo.beforePrice">￥{{cardInfo.beforePrice}}</text>
					<text class="card-price">￥{{cardInfo.price || '0.00'}}</text>
				</view>
				<view class="card-usage">
					<view class="usage-item" v-if="cardInfo.remainingTimes">
						<image src="/static/icons/times.png" mode="aspectFit" class="usage-icon"></image>
						<text class="usage-text">可用{{cardInfo.remainingTimes}}次</text>
					</view>
					<view class="usage-item" v-if="cardInfo.originalAmount">
						<image src="/static/icons/balance.png" mode="aspectFit" class="usage-icon"></image>
						<text class="usage-text">可用余额￥{{cardInfo.originalAmount}}</text>
					</view>
				</view>
			</view>
			<view class="card-image">
				<image :src="cardInfo.imgUrl || '/static/card-placeholder.png'" mode="aspectFit"></image>
			</view>
		</view>
		<!-- 卡片简介 -->
		<view class="card-intro">
			<view class="section-title">卡片简介</view>
			<view class="intro-content">
				<view class="intro-paragraph">
					{{cardInfo.description || '暂无描述'}}
				</view>
			</view>
		</view>
		<!-- 用卡须知 -->
		<view class="card-notice">
			<view class="section-title">用卡须知</view>
			<view class="notice-content">
				<view class="notice-item">
					<view class="notice-title">使用规则：</view>
					<view class="notice-text">{{cardInfo.useRule || '会员卡仅本人使用，不得转售、转让。消费时请主动出示会员卡，以便识别。'}}</view>
				</view>
				<view class="notice-item">
					<view class="notice-title">卡内余额：</view>
					<view class="notice-text">
						{{cardInfo.balanceRule || '会员卡充值金额长期有效，若卡内余额不足，可随时进行充值。充值金额不设上限，且充值后不可提现。'}}
					</view>
				</view>
				<view class="notice-item">
					<view class="notice-title">退卡规定：</view>
					<view class="notice-text">
						{{cardInfo.refundRule || '若会员要求退卡，需携带本人有效身份证件及会员卡至门店办理。退卡时将扣除已享受的优惠金额及相关手续费，剩余金额将在7个工作日内退还至原支付账户。'}}
					</view>
				</view>
				<view class="notice-item">
					<view class="notice-title">权益变更：</view>
					<view class="notice-text">
						{{cardInfo.rightsRule || '本店保留对会员卡权益及相关规则进行调整的权利，如有变更将提前在店内及线上平台公告，敬请会员关注。'}}
					</view>
				</view>
			</view>
		</view>
		<!-- 已购买提示 -->
		<view class="purchased-tip" v-if="hasPurchased">
			<text>您已购买此卡，请勿重复购买</text>
		</view>
		<view v-if="techRole" class="float-buy-btn" :class="{ 'disabled': hasPurchased }">
			<text style="font-size: 170%;">技师不可购买</text>
		</view>
		<!-- 悬浮购买按钮 -->
		<view v-if="!techRole" class="float-buy-btn" :class="{ 'disabled': hasPurchased }" @tap="requestPayment">
			<text>{{ hasPurchased ? '已购买' : '立即购买' }}</text>
			<view class="price-container">
				<text class="before-price" v-if="cardInfo.beforePrice">￥{{cardInfo.beforePrice}}</text>
				<text class="price">￥{{cardInfo.price || '0.00'}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/nav-bar/nav-bar.vue'
	export default {
		components: {
			NavBar
		},
		data() {
			return {
				techRole: false,
				cardInfo: {},
				cardId: null,
				isSubmitting: false,
				hasPurchased: false
			}
		},
		onLoad(options) {
			if (options.id) {
				this.cardId = options.id;
				this.getCardInfo();
			} else {
				uni.showToast({
					title: '参数错误',
					icon: 'none'
				});
			}
			// 处理支付结果回调
			if (options.paymentResult === 'success') {
				// 从缓存获取支付结果
				try {
					const paymentResult = uni.getStorageSync('paymentResult')
					if (paymentResult && paymentResult.success && paymentResult.sourcePageData) {
						// 支付成功，创建会员卡
						const userInfo = uni.getStorageSync('userInfo')
						if (userInfo && userInfo.memberId) {
							this.createMemberCard(userInfo.memberId, paymentResult.sourcePageData.cardId)
						}
						// 清除支付结果缓存
						uni.removeStorageSync('paymentResult')
					}
				} catch (e) {}
			}
			this.checkRole()
		},
		methods: {
			checkRole() {
				const userInfoStr = uni.getStorageSync('userInfo')
				if (userInfoStr === null) {
					uni.showToast({
						title: '请重新登录',
						icon: 'error',
						duration: 2000
					})
				} else {
					if (userInfoStr.role === 'technician') {
						this.techRole = true
					}
				}
			},
			// 获取会员卡详情
			getCardInfo() {
				uni.showLoading({
					title: '加载中...'
				});
				uni.request({
					url: `${uni.$config.baseUrl}/card/card/${this.cardId}`,
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							this.cardInfo = res.data.data;
							// 获取卡片信息后，检查用户是否已购买
							this.checkUserPurchased();
						} else {
							uni.showToast({
								title: res.data.msg || '获取会员卡信息失败',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.showToast({
							title: '网络请求失败，请检查网络',
							icon: 'none'
						});
					},
					complete: () => {
						uni.hideLoading();
					}
				});
			},
			// 检查用户是否已购买此卡
			checkUserPurchased() {
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo || !userInfo.memberId) {
					uni.showToast({
						title: '请先登录',
						icon: 'error',
						duration: 2000
					})
					return;
				}
				// 构建查询参数
				const queryParams = {
					memberId: userInfo.memberId,
					cardId: this.cardId,
					status: 1 // 1-正常状态
				}
				// 调用后端接口查询用户是否已购买此卡
				uni.request({
					url: `${uni.$config.baseUrl}/usercard/usercard/listByUid`,
					method: 'GET',
					data: queryParams,
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							// 检查返回的数据中是否有记录
							if (res.data.rows && res.data.rows.length > 0) {
								this.hasPurchased = true;
								uni.showToast({
									title: '您已购买此卡',
									icon: 'none',
									duration: 2000
								});
							} else {
								this.hasPurchased = false;
							}
						}
					}
				});
			},
			// 处理购买按钮点击
			requestPayment() {
				// 如果已购买，直接返回
				if (this.hasPurchased) {
					uni.showToast({
						title: '您已购买此卡，请勿重复购买',
						icon: 'none'
					});
					return;
				}
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo || !userInfo.memberId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				// 显示购买确认弹窗
				uni.showModal({
					title: '购买确认',
					content: `确定要购买${this.cardInfo.cardName}吗？价格：￥${this.cardInfo.price}`,
					success: (res) => {
						if (res.confirm) {
							// 构建支付参数
							const paymentData = {
								amount: this.cardInfo.price,
								orderType: 1, // 1-会员卡购买
								orderDesc: `购买${this.cardInfo.cardName}`,
								// 支付完成后直接回到当前卡详情页，以便触发 createMemberCard
								callbackUrl: `/pages/rechargeCard-list/rechargeCard-list?id=${this.cardId}`,
								paymentParams: {
									memberId: userInfo.memberId,
									cardId: this.cardId,
									amount: this.cardInfo.price,
									paymentMethod: 1, // 1-微信支付
									orderType: 1, // 1-会员卡购买
									orderSource: 1 // 1-H5
								},
								sourcePageData: {
									cardId: this.cardId,
									cardName: this.cardInfo.cardName
								}
							}
							// 使用缓存存储支付参数
							uni.setStorageSync('paymentData', paymentData)
							// 跳转到统一支付页面
							uni.navigateTo({
								url: `/pages/pay-public/pay-public?login=false`
							})
						}
					}
				})
			},
			// 创建会员卡
			createMemberCard(memberId, cardId) {
				// 显示加载中
				uni.showLoading({
					title: '处理中...'
				})
				// 构建会员卡用户数据
				const memberCardUser = {
					memberId: memberId,
					cardId: cardId,
					status: 1 // 1-正常
				}
				// 调用后端接口
				uni.request({
					url: `${uni.$config.baseUrl}/usercard/usercard`,
					method: 'POST',
					data: memberCardUser,
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							uni.showToast({
								title: '购买成功',
								icon: 'success',
								duration: 2000,
								success: () => {
									setTimeout(() => {
										uni.switchTab({
											url: '/pages/index/index'
										})
									}, 2000)
								}
							})
						} else {
							uni.showToast({
								title: res.data.msg || '购买失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('购买失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.recharge-card {
		min-height: 100vh;
		background: #F8F8F8;
		padding-bottom: 30rpx;

		.card-header {
			background: #FFFFFF;
			padding: 30rpx;

			.card-title {
				font-size: 36rpx;
				color: #333;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.price-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
			}

			.price-container {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.before-price {
					font-size: 28rpx;
					color: #999;
					text-decoration: line-through;
					margin-right: 12rpx;
				}

				.card-price {
					font-size: 40rpx;
					color: #2B87FF;
					font-weight: bold;
				}
			}

			.card-usage {
				display: flex;
				flex-direction: column;
				gap: 8rpx;

				.usage-item {
					display: flex;
					align-items: center;
					background: rgba(43, 135, 255, 0.1);
					padding: 6rpx 12rpx;
					border-radius: 20rpx;

					.usage-icon {
						width: 28rpx;
						height: 28rpx;
						margin-right: 6rpx;
					}

					.usage-text {
						font-size: 24rpx;
						color: #2B87FF;
					}
				}
			}

			.card-image {
				width: 100%;
				height: 600rpx;
				background: #F5F5F5;
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					width: 80%;
					height: 80%;
				}
			}
		}

		.card-benefits {
			margin-top: 20rpx;
			background: #FFFFFF;
			padding: 30rpx;

			.section-title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
				margin-bottom: 30rpx;
			}

			.benefits-list {
				display: flex;
				justify-content: space-between;

				.benefit-item {
					display: flex;
					flex-direction: column;
					align-items: center;

					.benefit-icon {
						width: 80rpx;
						height: 80rpx;
						margin-bottom: 10rpx;
					}

					.benefit-name {
						font-size: 26rpx;
						color: #666;
					}
				}
			}
		}

		.card-intro {
			margin-top: 20rpx;
			background: #FFFFFF;
			padding: 30rpx;

			.section-title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.intro-content {
				.intro-paragraph {
					font-size: 28rpx;
					color: #666;
					line-height: 1.6;
					margin-bottom: 20rpx;

					&:last-child {
						margin-bottom: 0;
					}
				}
			}
		}

		.card-notice {
			margin-top: 20rpx;
			background: #FFFFFF;
			padding: 30rpx;

			.section-title {
				font-size: 32rpx;
				color: #333;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.notice-content {
				.notice-item {
					margin-bottom: 20rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.notice-title {
						font-size: 28rpx;
						color: #333;
						font-weight: 500;
						margin-bottom: 8rpx;
					}

					.notice-text {
						font-size: 26rpx;
						color: #666;
						line-height: 1.6;
					}
				}
			}
		}

		.purchased-tip {
			margin: 20rpx;
			padding: 20rpx;
			background: #FFF7E6;
			border-radius: 8rpx;
			text-align: center;
			color: #FA8C16;
			font-size: 28rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		}

		.float-buy-btn {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			height: 100rpx;
			background: linear-gradient(135deg, #2B87FF, #1976D2);
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
			z-index: 100;

			text {
				color: #FFFFFF;
				font-size: 32rpx;
				font-weight: 500;
			}

			.price-container {
				display: flex;
				align-items: center;
				margin-left: 20rpx;

				.before-price {
					font-size: 24rpx;
					color: rgba(255, 255, 255, 0.7);
					text-decoration: line-through;
					margin-right: 8rpx;
				}

				.price {
					font-size: 40rpx;
					font-weight: bold;
				}
			}

			&:active {
				opacity: 0.9;
			}

			&.disabled {
				background: #CCCCCC;
				opacity: 0.8;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}
</style>